<style type="text/css" title="currentStyle">
	@import "../media/css/demo_table.css";
	@import "media/css/TableTools.css";
</style>

<script type="text/javascript" charset="utf-8" src="../media/js/jquery.dataTables.js"></script>
<script type="text/javascript" charset="utf-8" src="media/ZeroClipboard/ZeroClipboard.js"></script>
<script type="text/javascript" charset="utf-8" src="media/js/TableTools.js"></script>
<script type="text/javascript" charset="utf-8">
	$(document).ready( function () {
		$('#tableContact').dataTable();
	} );
</script>
<?php
//print_r($_POST);
if(isset($_POST[txtAssRouteId]) && $_POST[txtAssRouteId] !='')
{
	$sql = "SELECT * FROM tb_route_info where tri_id =".$_POST[txtAssRouteId];
	$rows = $db->query($sql);
	$userRecord = $db->fetch_array($rows);
	//print_r($userRecord);

	//echo 'ss'.strpos($userRecord[tri_alertDays], '1');
	$spltTime1 = explode("#",$userRecord[tri_mornTripTime]);
	$spltTime2 = explode("#",$userRecord[tri_evenTripTime]);
	$days = explode(",",$userRecord[tri_alertDays]);
	//$readonly = 'readonly="readonly"';
}
if($recordUserInfo[ci_clientType] == "Client" && $recordUserInfo[ui_isAdmin] == "1")
{
	$devices_query =  "SELECT * FROM tb_deviceinfo,tb_client_subscription WHERE tcs_isActive = 1 AND tcs_deviceId = di_id AND di_clientId =".$_SESSION[clientID]." AND di_status = 1 ORDER BY di_deviceName,di_deviceId ASC";
}
else if($recordUserInfo[ci_clientType] == "Client" && $recordUserInfo[ui_isAdmin] == "0" && $recordUserInfo[ui_roleId] == "1")
{
	$devices_query = "SELECT * FROM tb_deviceinfo,tb_client_subscription WHERE tcs_isActive = 1 AND tcs_deviceId = di_id AND di_status = 1 AND di_clientId=".$_SESSION[clientID]." AND di_assignedUserId = ".$_SESSION[userID]." ORDER BY di_deviceName,di_deviceId ASC";
}
//echo $devices_query;
//$devices_query =  "SELECT * FROM tb_deviceinfo WHERE di_clientId =".$_SESSION[clientID]." AND di_status = 1 ORDER BY di_deviceName,di_deviceId ASC";
$devices_resp = mysql_query($devices_query);	

?> 

<script type="text/javascript" language="javascript">

function showPreloader()
{
	var returnVal = validateMapReport()
	if(returnVal == 1)
		return true;
	else return false;
}

jQuery(function() 
{

 $("#time3, #time4").timePicker({
  startTime: "00:01 AM", // Using string. Can take string or Date object.
  endTime: "11:59 PM", // Using Date object here.
  show24Hours: false,
  separator: ':',
  step: 1});    
	
var oldTime = $.timePicker("#time3").getTime();

$("#time3").change(function() {
  if ($("#time4").val()) { // Only update when second input has a value.
	// Calculate duration.
	var duration = ($.timePicker("#time4").getTime() - oldTime);
	var time = $.timePicker("#time3").getTime();
	// Calculate and update the time in the second input.
	$.timePicker("#time4").setTime(new Date(new Date(time.getTime() + duration)));
	oldTime = time;
  }
});
// Validate.
$("#time4").change(function() {
  if($.timePicker("#time3").getTime() > $.timePicker(this).getTime()) {
	$(this).addClass("error");
  }
  else {
	$(this).removeClass("error");
  }
});


 $("#time1, #time2").timePicker({
  startTime: "00:01 AM", // Using string. Can take string or Date object.
  endTime: "11:59 PM", // Using Date object here.
  show24Hours: false,
  separator: ':',
  step: 1});    
	
var oldTime = $.timePicker("#time1").getTime();

$("#time1").change(function() {
  if ($("#time2").val()) { // Only update when second input has a value.
	// Calculate duration.
	var duration = ($.timePicker("#time2").getTime() - oldTime);
	var time = $.timePicker("#time1").getTime();
	// Calculate and update the time in the second input.
	$.timePicker("#time2").setTime(new Date(new Date(time.getTime() + duration)));
	oldTime = time;
  }
});
// Validate.
$("#time2").change(function() {
  if($.timePicker("#time1").getTime() > $.timePicker(this).getTime()) {
	$(this).addClass("error");
  }
  else {
	$(this).removeClass("error");
  }
});

});

function validateMapReport()
{
	if(document.getElementById('txtRouteName').value== "" )
	{
		alert("Enter Routename"); 
		document.getElementById('txtRouteName').focus();
		return 0;  
	}
	if(document.getElementById('map_device_id').value== 0 )
	{
		alert("Select Device"); 
		document.getElementById('map_device_id').focus();
		return 0;  
	}
	if(document.getElementById('time3').value != "" && document.getElementById('time4').value !="")
	{
	var frmTime1 = document.getElementById('time3').value.split(" ");   
	var frmTime2 = frmTime1[0].split(":");
	if(frmTime1[1] == "PM")
	{
		newFrmTime = ((eval(frmTime2[0]) + 12 ) * 60) + eval(frmTime2[1]);
	}
	else
	{
		if(eval(frmTime2[0]) >=12)
		{
			frmTime2[0] = eval(frmTime2[0]) - 12;
		}
			
		newFrmTime = (eval(frmTime2[0])*60) + eval(frmTime2[1]);
	}
		
	var toTime1 = document.getElementById('time4').value.split(" ");   
	var toTime2 = toTime1[0].split(":");
	if(toTime1[1] == "PM")
	{
		newtoTime = (( eval(toTime2[0]) + 12 ) * 60) + eval(toTime2[1]);
	}
	else
	{
		if(eval(toTime2[0]) >= 12 )
		{
			toTime2[0] = eval(toTime2[0]) - 12;
		}
		newtoTime = (eval(toTime2[0])*60) + eval(toTime2[1]);
	}
	
	/*var days_diff = newtoTime - newFrmTime;
	if(days_diff < 0)
	{ 
	 	alert("Input Time is wrong. It should be in a same day. like: 9:30 AM to 5:00 PM");
	 	document.getElementById('time4').select();
	 	return 0;
	}*/
	}
	
	if(document.getElementById('time1').value != "" && document.getElementById('time2').value !="")
	{
	var frmTime1 = document.getElementById('time1').value.split(" ");   
	var frmTime2 = frmTime1[0].split(":");
	if(frmTime1[1] == "PM")
	{
		newFrmTime = ((eval(frmTime2[0]) + 12 ) * 60) + eval(frmTime2[1]);
	}
	else
	{
		if(eval(frmTime2[0]) >=12)
		{
			frmTime2[0] = eval(frmTime2[0]) - 12;
		}
			
		newFrmTime = (eval(frmTime2[0])*60) + eval(frmTime2[1]);
	}
		
	var toTime1 = document.getElementById('time2').value.split(" ");   
	var toTime2 = toTime1[0].split(":");
	if(toTime1[1] == "PM")
	{
		newtoTime = (( eval(toTime2[0]) + 12 ) * 60) + eval(toTime2[1]);
	}
	else
	{
		if(eval(toTime2[0]) >= 12 )
		{
			toTime2[0] = eval(toTime2[0]) - 12;
		}
		newtoTime = (eval(toTime2[0])*60) + eval(toTime2[1]);
	}
	
	/*var days_diff = newtoTime - newFrmTime;
	if(days_diff < 0)
	{ 
	 	alert("Input Time is wrong. It should be in a same day. like: 9:30 AM to 5:00 PM");
	 	document.getElementById('time2').select();
	 	return 0;
	}*/
	}
	if(document.getElementById('txtGeoIds').value == "")
	{
		alert("Select Geofence"); 
		document.getElementById('selGeofenceId').focus();
		return 0;  
	}
	if(document.getElementById('txtDayIds').value == "")
	{
		alert("Select week days"); 
		document.getElementById('chkDay0').focus();
		return 0;  
	}
	return 1;
	
}

var ajax1=new sack();
function submitAlertType(val)
{
	ajax1.requestFile = 'ajax_server.php?contType='+val;			
	//alert(ajax1.requestFile);
	ajax1.onCompletion = function(){getSource()};
	ajax1.runAJAX();
}
function getSource()
{
	document.getElementById('txtMobiEmail').value="";
	document.getElementById('selContId').innerHTML = ajax1.response;
}
function getDeviceDetails(geoid)
{
	if(geoid != 0)
	{
		qry = "select * from tb_route_info where tri_deviceId  = "+geoid;
		ajax1.requestFile = 'ajax_server.php?ajaxQry='+qry;
		//alert(ajax1.requestFile);
		ajax1.onCompletion = function(){resultDevice()};
		ajax1.runAJAX();
	}
}
function resultDevice()
{
  if(ajax1.response > 0 )
  {
  	alert("Selected device already assigned in another route. Please choose some another device");
	document.getElementById('map_device_id').focus();
  }
	
}
function changeSts(id,span,uid)
{
	if(document.getElementById(id).checked)
		status = 1;
	else
		status = 0;
		
	ajax1.requestFile = 'ajax_server.php?upGeoStatus=y&geoid='+uid+'&status='+status;
	//alert(ajax1.requestFile);
	ajax1.onCompletion = function(){resultGeoStatus(span,id)};
	ajax1.runAJAX();
}
function resultGeoStatus(span,id)
{
  //alert(ajax1.response)	
  if(ajax1.response == 4)
  {
	 alert("Status Updated Successfully.");
	 if(document.getElementById(id).checked) 
	  	document.getElementById(span).innerHTML = 'Deactive';
	 else 
		document.getElementById(span).innerHTML = 'Active';
	
	document.getElementById('selGeofenceId').innerHTML = "<option value=0>Loading...</option>";
	window.location.href = "?ch=assignGeofence";
  }
  else
  {
	  alert("Status Not Updated. Because this geofence mmight assigned to some other device");
	  window.location.href = "?ch=assignGeofence";
  }
	
}
function sendCSVData()
{
//alert(c1);
document.frmTripData.submit();
//	window.location.href='export.php?csvData='+c1+'&frdate='+c2+'&frtime='+c3+'&totime='+c4+'&vehino='+c5;
	//document.write('export.php?csvData='+c1+'&frdate='+c2+'&frtime='+c3+'&totime='+c4+'&vehino='+c5);
}
function changeGeoValue()
{
	var tmpId = '';
	for (i=0; i<document.getElementById('selGeofenceId').length;i++)
	{
		if (document.getElementById('selGeofenceId').options[i].selected)
		{
			if(i==0)
				tmpId = document.getElementById('selGeofenceId').options[i].value+"#";
			else
				tmpId +=document.getElementById('selGeofenceId').options[i].value+"#";
		}
	}
	document.getElementById('txtGeoIds').value = tmpId;
}
function addThisDay(e)
{
	if(e.checked)
	{
		if(document.getElementById('txtDayIds').value=="")
			document.getElementById('txtDayIds').value = e.value+",";
		else
			document.getElementById('txtDayIds').value += e.value+",";
	}
	else
	{
		document.getElementById('txtDayIds').value = document.getElementById('txtDayIds').value.replace(e.value+",","")
	}
	/*var tmpId = '';
	var sel = 0;
	
	for (i=0; i<7;i++)
	{
		if (document.getElementById('selContId').options[i].selected)
		{
			if(sel < 4)
			{
				if(i==0)
					tmpId = document.getElementById('txtDayIds').options[i].value+",";
				else
					tmpId +=document.getElementById('txtDayIds').options[i].value+",";
				
				sel++;
			}
			else
			{
				document.getElementById('txtDayIds').options[i].selected = false;
				alert("Any 4 contacts only allowed to choose");
				sel--;
			}
		}
	}
	document.getElementById('txtMobiEmail').value = tmpId;*/
}
var ajax1=new sack();
function showPoints(f,s)
{
	//ajax1.requestFile = 'ajax_server.php?addGeoPoint=y&param='+f+'&name='+s;
	//document.write(ajax1.requestFile);
	/*var tableData = "";
	var f1 = f.split("@");
	for(i = 0; i < f1.length-1; i++)
	{
		//tableData = '<tr><td>'+i+'</td><td><input type="checkbox" name="param'+i+'" id="param'+i+'"></td><td><input type="text" name="param'+i+'" id="param'+i+'" /></td></tr>';
		tableData = '<tr><td>'+i+'</td><td><input type="checkbox" name="param'+i+'" id="param'+i+'"></td><td><input type="text" name="param'+i+'" id="param'+i+'" value="'+s[i]+'" /></td></tr>';
	}
	document.getElementById('paramTable').innerHTML= tableData;*/
}
</script>
<div class="pagearea">
<form id="frm_map_filter" name="frm_map_filter" method="post" action="?ch=Assign" onsubmit="return validateMapReport();">   
<input type="hidden" name="txtAssRouteId" id="txtAssRouteId" value="<?php echo $_POST[txtAssRouteId];?>" /> 
<table class="gridform_final">
    <tr height="70%"><th colspan="2">Assign Route</th></tr>
    
  <tr>
  	<td width="35%">Route Name</td> 
    <td width="35%"><input type="text" name="txtRouteName" style="width:40%" id="txtRouteName" value="<?php echo $userRecord[tri_routeName]; ?>" /></td> 
  </tr>
  <tr>
    <td width="35%">Select Device&nbsp;</td>     
      <td>
        <select name="map_device_id" id="map_device_id" tabindex="1" style="width:40%" onchange="getDeviceDetails(this.value)">
        <option value="0">Select Device</option>
         <?php
		while($devices_fetch = @mysql_fetch_assoc($devices_resp)) 
		{ 
			if($devices_fetch[di_deviceName])
				$devName = $devices_fetch[di_deviceName];
			else
				$devName = $devices_fetch[di_deviceId];
        ?>
        <option value="<?php echo $devices_fetch[di_id]; ?>" 
        <?php if($userRecord[tri_deviceId] == $devices_fetch[di_id]) echo 'selected="selected"'; ?>><?php echo 	$devName; ?></option>
        <?php } ?>		
        </select>
        <input type="hidden" name="curdate" id="curdate" value="<?php echo date('Y-m-d'); ?>" />
    </td>
  </tr>
   <tr>
    <td>Morning Trip Time</td>
      <td>      
    	<table class="grid" style="width:50%;">
          <tr>
            <td width="10%" style="border:0px; vertical-align:middle;">From</td>
            <td width="40%" style="border:0px; vertical-align:middle;"><span><input type="text" name="time3" id="time3" style="width:60%" readonly="true" tabindex="2" value="<?php if($spltTime1[0]) echo $spltTime1[0]; else echo "10:00 AM";?>" /></span></td>
            <td width="10%" align="center" style="border:0px; vertical-align:middle;">To</td>
            <td width="40%" style="border:0px; vertical-align:middle;"><span><input type="text" name="time4" id="time4" style="width:60%" readonly="true" tabindex="3" value="<?php if($spltTime1[1]) echo $spltTime1[1]; else echo "06:00 PM";?>" /></span></td>
          </tr>
        </table>      
    </td>
    </tr> 
    <tr>
    <td>Evening Trip Time </td>
      <td>      
    	<table class="grid" style="width:50%;">
          <tr>
            <td width="10%" style="border:0px; vertical-align:middle;">From</td>
            <td width="40%" style="border:0px; vertical-align:middle;"><span><input type="text" name="time1" id="time1" style="width:60%" readonly="true" tabindex="2" value="<?php if($spltTime2[0]) echo $spltTime2[0]; else echo "10:00 AM";?>" /></span></td>
            <td width="10%" align="center" style="border:0px; vertical-align:middle;">To</td>
            <td width="40%" style="border:0px; vertical-align:middle;"><span><input type="text" name="time2" id="time2" style="width:60%" readonly="true" tabindex="3" value="<?php if($spltTime2[1]) echo $spltTime2[1]; else echo "06:00 PM";?>" /></span></td>
          </tr>
        </table>      
    </td>
    </tr>
               
  <tr>
    <td>Select Geofence</td>
     <td  >
        <select name="selGeofenceId" id="selGeofenceId" tabindex="5" style="width:50%" multiple="multiple" onchange="changeGeoValue()" >
		 <?php 
        $getGeofence =  "SELECT * FROM tb_geofence_info WHERE tgi_isActive = 1 AND tgi_clientId =".$_SESSION[clientID]." ORDER BY tgi_name ASC";
        $resGeofence = mysql_query($getGeofence);
        while($fetGeofence = @mysql_fetch_assoc($resGeofence)) 
        { 
            if(isset($_POST[txtAssRouteId]))
            {
                $geoArr = explode("#",$userRecord[tri_geofenceIds]);
                if(in_array($fetGeofence[tgi_id],$geoArr))
                {
                    $select = 'selected="selected"';
                }
                else $select ='';
            }
        ?>
        <option value="<?php echo $fetGeofence[tgi_id];?>" <?php echo $select ?>><?php echo $fetGeofence[tgi_name]; ?></option>
        <?php } ?>		
        </select>
        <input type="hidden" name="txtGeoIds" id="txtGeoIds" value="<?php echo $userRecord[tri_geofenceIds];?>" />
    </td>
   </tr>
   <tr>
    <td>Select weekly working Days </td>
     <td>
        <input type="checkbox" name="chkDay0" id="chkDay0" value="0" onclick="addThisDay(this)" <?php if(strpos($userRecord[tri_alertDays], '0') !== false) echo 'checked=checked'; ?> />&nbsp;Sunday
        <input type="checkbox" name="chkDay1" id="chkDay1" value="1" onclick="addThisDay(this)" <?php if(strpos($userRecord[tri_alertDays], '1') !== false) echo 'checked=checked'; ?>/>&nbsp;Monday
        <input type="checkbox" name="chkDay2" id="chkDay2" value="2" onclick="addThisDay(this)" <?php if(strpos($userRecord[tri_alertDays], '2') !== false) echo 'checked=checked'; ?>/>&nbsp;Tuesday
        <input type="checkbox" name="chkDay3" id="chkDay3" value="3" onclick="addThisDay(this)" <?php if(strpos($userRecord[tri_alertDays], '3') !== false) echo 'checked=checked'; ?>/>&nbsp;Wednesday
        <input type="checkbox" name="chkDay4" id="chkDay4" value="4" onclick="addThisDay(this)" <?php if(strpos($userRecord[tri_alertDays], '4') !== false) echo 'checked=checked'; ?>/>&nbsp;Thursday
        <input type="checkbox" name="chkDay5" id="chkDay5" value="5" onclick="addThisDay(this)" <?php if(strpos($userRecord[tri_alertDays], '5') !== false) echo 'checked=checked'; ?>/>&nbsp;Friday
        <input type="checkbox" name="chkDay6" id="chkDay6" value="6" onclick="addThisDay(this)" <?php if(strpos($userRecord[tri_alertDays], '6') !== false) echo 'checked=checked'; ?>/>&nbsp;Saturday
        <input type="hidden" name="txtDayIds" id="txtDayIds" value="<?php echo $userRecord[tri_alertDays];?>" />
    </td>
   </tr>
  <tr>
    <td height="33" colspan="2" style="text-align:center">
    <?php if(isset($_POST[txtAssRouteId]) && $_POST[txtAssRouteId]!='') { ?>
    <input type="submit" name="cmdUpdateAssignRoute" id="cmdUpdateAssignRoute" value="Update" class="save_btn" tabindex="7" onclick="return showPreloader();" />
    <?php } else { ?>
    <input type="submit" name="cmdAddAssignRoute" id="cmdAddAssignRoute" value="Add" class="save_btn" tabindex="7" onclick="return showPreloader();" />
    <?php } ?>
    <input type="button" name="cmdCancel" id="cmdCancel" value="Cancel" class="save_btn" onclick="location.href='?ch=viewRoute';" tabindex="8" /> 
	</td>
  </tr>
</table>

<table width="100%">
<tr>
<td width="49%" valign="top" style="vertical-align: top;">

</td>
<td width="1%">&nbsp;</td>

</tr>
</table>
</form>
</div>	
<form name="frmGeofenceId" id="frmGeofenceId" method="post">
	<input type="hidden" name="map_device_id" id="map_device_id" />
    <input type="hidden" name="alrtType" id="alrtType" />
    
    <input type="hidden" name="selNoofAlert" id="selNoofAlert" />
    <input type="hidden" name="time3" id="time3" />
    <input type="hidden" name="time4" id="time4" />
    <input type="hidden" name="txtGeoIds" id="txtGeoIds" />
    <input type="hidden" name="txtMobiEmail" id="txtMobiEmail" />
</form>